/*
 * EmployeeAemFinder.cpp
 *
 *  Created on: 20 ��� 2010
 *      Author: Sartios
 */

#include "EmployeeAemDbFinder.h"
#include "../../../OdbcConnectionSingleton/OdbcConnectionSingleton.h"
#include "../../../DbElementProvider/DbElementProvider.h"
#include "../../../../Utilities/ConvertTypes/ConvertType.h"

EmployeeAemDbFinder::EmployeeAemDbFinder() {
	const string DB_NAME = *DbElementProvider::getInstance()->getDbName();
	const string USERNAME = *DbElementProvider::getInstance()->getUsername();
	const string PASSWORD = *DbElementProvider::getInstance()->getPassword();

	bool ret = OdbcConnectionSingleton::getInstance()->connect(&DB_NAME,&USERNAME,&PASSWORD);
	if(!ret){
		throw;
	}

}

EmployeeAemDbFinder::~EmployeeAemDbFinder() {

}

EmployeeAemDbFinder::EmployeeAemDbFinder(const string *dbName,const string *username,const string *password){
	if((0!=dbName)&&(0!=username)&&(0!=password)){
		bool ret = OdbcConnectionSingleton::getInstance()->connect(dbName,username,password);
		if(!ret){
			throw;
		}
	}
}

string	*	EmployeeAemDbFinder::getNextValidAem()const{
	SQLHANDLE stmtHandle = OdbcConnectionSingleton::getInstance()->getStmtHandle();
	SQLRETURN rc;

	char key[255];
	string *code=0;

	string sqlString="SELECT MAX(CAST(aem AS SIGNED)) FROM employees";

	rc = SQLExecDirect(stmtHandle, (SQLTCHAR *)sqlString.c_str(), SQL_NTS);
	if(rc==SQL_SUCCESS){
		//We know that the 1st column of the query we sent is the aem
		SQLBindCol(stmtHandle, 1, SQL_C_CHAR, (SQLPOINTER) key, sizeof(key), NULL);
		if((rc  = SQLFetch(stmtHandle))!= SQL_NO_DATA) {
			code=new string(key);
			ConvertType *ct=new ConvertType();
			code=ct->toString(1+(ct->toInt(code)));
			delete ct;
		}
	}
	return code;
}
